package com.thghh.gkrpc;

import com.tghhh.gkrpc.Request;
import com.tghhh.gkrpc.ServiceDescriptor;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 服务管理类
 * @author Zhikang.Peng
 * @version 1.0
 * @email thghh@qq.com
 * @date 2020/4/13 16:17
 */
@Slf4j
public class ServiceManager {
    private Map<ServiceDescriptor, ServiceInstance> serviceMap;

    public ServiceManager() {
        serviceMap = new ConcurrentHashMap<>();
    }

    /**
     * <p>注册服务,将bean的每一个公共方法注册成一个服务，保存在Map中
     * key是{@link ServiceDescriptor}一个服务的描述,
     * value:是{@link ServiceInstance}一个具体服务的实例
     * @param interfaceClass
     * @param bean
     * @param <T>
     */
    public <T> void registerService(Class<T> interfaceClass, T bean) {
        Method[] methods = ReflectionUtils.getPublicMethods(interfaceClass);
        for (Method method : methods) {
            ServiceInstance serviceInstance = new ServiceInstance(bean, method);
            ServiceDescriptor serviceDescriptor = ServiceDescriptor.from(interfaceClass, method);

            serviceMap.put(serviceDescriptor, serviceInstance);
            log.info("register service {} {}", serviceDescriptor.getClazz(), serviceDescriptor.getMethod());
        }
    }

    /**
     * 查看服务，获取服务实例
     *
     * @param request
     * @return
     */
    public ServiceInstance lookupService(Request request) {
        ServiceDescriptor serviceDescriptor = request.getService();
        return serviceMap.get(serviceDescriptor);
    }

}
